package com.whfc.emp.xxl.job;

import com.alibaba.fastjson.JSONObject;
import com.whfc.XxlJobConfig;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.HttpUtil;
import com.whfc.emp.dao.AppFaceGateMapper;
import com.whfc.emp.dao.AppFaceGateRecordMapper;
import com.whfc.emp.dto.AppFaceGateDTO;
import com.whfc.emp.dto.AppFaceGateRecordDTO;
import com.whfc.emp.dto.AppJXEmpDTO;
import com.whfc.emp.entity.AppEmp;
import com.whfc.emp.entity.AppFaceGateRecord;
import com.whfc.emp.param.EmpAttendSyncDataParam;
import com.whfc.emp.service.AppEmpService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @Description: 从九象获取刷脸记录定时任务
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/9/9 10:44
 */
@Component
@ConditionalOnBean(XxlJobConfig.class)
public class EmpJxDataJob {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppEmpService appEmpService;

    @Autowired
    private AppFaceGateRecordMapper appFaceGateRecordMapper;

    @Autowired
    private AppFaceGateMapper appFaceGateMapper;
    /**
     * 拉取九象人脸数据
     */
    @XxlJob("getJXEmpData")
    public void refreshEmpDeviceNetState() {
        try {
            Date endDate = new Date();;
            Date startDate=DateUtil.addMinutes(endDate,-1);;
            // 获取九象最近的一条数据
//            AppFaceGateRecordDTO lates = appFaceGateRecordMapper.selectLatestByDeptId(27);
//            if (lates==null){
//                endDate = new Date();
//                startDate = DateUtil.addMinutes(endDate,-1);
//            }else {
//                startDate = lates.getShowTime();
//                endDate = DateUtil.addMinutes(lates.getShowTime(),1);
//            }
            String startTime = DateUtil.formatDateTime(startDate);
            String endTime = DateUtil.formatDateTime(endDate);
            logger.info("本次同步九象人脸数据开始时间：{},结束时间：{}",startTime,endTime);
            List<AppJXEmpDTO> attendanceList = getAttendanceList(startTime,endTime);
            logger.info("本次拉取九象人脸的数据大小:{}", attendanceList.size());
            for (AppJXEmpDTO appJXEmpDTO : attendanceList) {
                // 获取身份证
                String idCard = appJXEmpDTO.getIdCard();
                // 基于身份证获取人员信息
                AppEmp appEmp = appEmpService.selectByDeptIdAndIdCardNo(27,idCard);
                if (appEmp == null) {
                    logger.info("未获取到人员的身份证============：{}",idCard);
                    continue;
                }
                // 如果人员编码不一样，则同步
                if (!appJXEmpDTO.getEmployeeId().equals(appEmp.getEmpCode())) {
                    // 设置人员编码
                    appEmp.setEmpCode(appJXEmpDTO.getEmployeeId());
                    appEmpService.updateById(appEmp);
                }

                EmpAttendSyncDataParam empAttendSyncDataParam = new EmpAttendSyncDataParam();
                empAttendSyncDataParam.setDeptId(27);
                empAttendSyncDataParam.setPersonGuid(appJXEmpDTO.getEmployeeId());
                // 考勤设备序列号
                String deviceKey = appJXEmpDTO.getHardwareId();
                AppFaceGateDTO appFaceGateDTO = appFaceGateMapper.selectByDeptIdAndDeviceKey(27, deviceKey);
                if (appFaceGateDTO != null) {
                    empAttendSyncDataParam.setFaceGateId(appFaceGateDTO.getFaceGateId());
                }
                empAttendSyncDataParam.setDeviceKey(deviceKey);
                empAttendSyncDataParam.setShowTime(appJXEmpDTO.getDatetime());
                empAttendSyncDataParam.setDirection(appJXEmpDTO.getWay());
                empAttendSyncDataParam.setPicture(appJXEmpDTO.getImage());
                empAttendSyncDataParam.setData(appJXEmpDTO.getId()+"");
                // 判断是否新增过
                if (StringUtils.hasText(appJXEmpDTO.getImage())) {
                    AppFaceGateRecord appFaceGateRecord = appFaceGateRecordMapper.selectByDataId(27, String.valueOf(appJXEmpDTO.getId()));
                    // 如果不为null  说明已经新增过了
                    if (appFaceGateRecord != null ){
                        continue;
                    }
                }
                appEmpService.attendanceSave(empAttendSyncDataParam);


            }

        } catch (Exception ex) {
            logger.error("拉取九象人脸的数据任务,出现异常", ex);
        }
    }

    public static void main(String[] args) {
        Date endDate = new Date();
        Date startDate = DateUtil.addHours(endDate, -4);
        List<AppJXEmpDTO> attendanceList = getAttendanceList(DateUtil.formatDateTime(startDate),DateUtil.formatDateTime(endDate));
        System.out.println(attendanceList.size());
        long count = attendanceList.stream().map(AppJXEmpDTO::getEmployeeName).distinct().count();
        int a = 1;
        for (AppJXEmpDTO appJXEmpDTO : attendanceList) {
            System.out.println("第"+a+"个人"+appJXEmpDTO);
            a++;
        }

    }

    private static List<AppJXEmpDTO> getAttendanceList(String startDate,String endDate){
        Long orgId = 1638423405883L;
        String appId = "jx1639362873537";
        String appSecret = "5D7B80E497EC78C32C6D3762A22D056D";
        String version = "v1";
        String method = "labor";
        // 获取过去三秒的数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orgId",orgId);
        jsonObject.put("pageNum",1);
        jsonObject.put("pageSize",50);
        jsonObject.put("startDatetime",startDate);
        jsonObject.put("endDatetime",endDate);
        String jsonString = JSONObject.toJSONString(jsonObject);
        long timestamp = System.currentTimeMillis();
        String sign = encrypt(appSecret + "appId=" + appId + "&version=" + version + "&method=" + method + "&timestamp=" + timestamp + "&data=" + jsonString+appSecret);
        String url  = "http://jiuxiang.9xsmart.com/smart-api/v1/labor/attendance/record/listEnterOutRecordPage?";
        String requestUrl = String.format( "appId=%s&version=v1&method=labor&timestamp=%s&sign=%s", appId, timestamp, sign);
        // http://xxxxxx:8080/v1/employee/listAll?appId=appId&version=version&method=method&timestamp=timestamp&sign=sign
        String result = HttpUtil.doPost(url+requestUrl, jsonString);
        JSONObject jsonData = JSONObject.parseObject(result);
        if (200 != jsonData.getInteger("code")) {
            return new ArrayList<>();
        }
        JSONObject data = jsonData.getJSONObject("data");
        List<AppJXEmpDTO> list = data.getJSONArray("list").toJavaList(AppJXEmpDTO.class);
        return list;
    }

    public static String encrypt(String content) {
        try {
            // Create MD5 Hash
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(content.getBytes());
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++)
                hexString.append(String.format("%02X", 0xFF &
                        messageDigest[i]));
            return hexString.toString().toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
